

const http = require("http");
const fs = require("fs");
const axios = require("axios");
const cheerio = require("cheerio");
const stream = require("stream");
const url = require("url");
const mongoClient = require("mongodb").MongoClient;
const streamToBuffer = require('stream-to-buffer');
const bll = require("./bll");


async function getWebFileStream (url) {
    let config = {
        responseType: "stream"
    };
    let response = await axios.get(url, config);
    return response.data;
}
function streamToBufferAsync (myStream) {
    return new Promise((resolve, reject) => {
        streamToBuffer(myStream, (err, buf) => {
            if (err) {
                return reject(err);
            }
            else {
                return resolve(buf);
            }
        });
    });
}
function getUserInfo ($page) {
    let $totalInfo = $page(".total-info");

    let nickName = $totalInfo.children("h2").text();
    let nickNameHtml = $totalInfo.children("h2").html();
    let kuaiShouAccount = $totalInfo.children("p").text();

    let $workInfo = $totalInfo.children(".work-info");
    let $divs = $workInfo.children("div");
    let fansNum = $divs.eq(0).find("p.num").text();
    let followNum = $divs.eq(1).find("p.num").text();
    let worksNum = $divs.eq(2).find("p.num").text();

    let $a = $totalInfo.find(".img-wrap > a");
    let kuaiShouUserUrl = $a.attr("href");
    let pathArray = kuaiShouUserUrl.split("/");
    let kuaiShouId = pathArray[pathArray.length - 1];
    let headImgUrl = $a.find("img").attr("src");

    return {
        kuaiShouId: kuaiShouId,
        nickName: nickName,
        nickNameHtml: nickNameHtml,
        kuaiShowAccount: kuaiShouAccount,
        fansNum: fansNum,
        followNum: followNum,
        worksNum: worksNum,
        headImgUrl: headImgUrl
    };
}
function getOtherWorks ($page) {
    let $photoList = $page(".photo-list");

    let rtv = [];

    let $aArray = $photoList.find("li > a");
    for (let i = 0; i < $aArray.length; ++i) {
        let $a = $aArray.eq(i);
        let pagePath = $a.attr("href");
        let imgCss = $a.css("background-image");
        let op = imgCss.indexOf("http");
        let ed = imgCss.lastIndexOf(")");
        let imgUrl = imgCss.slice(op, ed);

        let pathList = pagePath.split("/");
        let worksId = pathList[pathList.length - 1];
        let kuaishouId = pathList[pathList.length - 2];

        rtv[i] = {
            kuaishouId: kuaishouId,
            worksId: worksId,
            pagePath: getBasePageUrl() + pagePath,
            imgUrl: imgUrl
        };
    }

    return rtv;
}
function getVideo () {
}
function getComments () {
}

function getBasePageUrl () {
    // let requestUrl = url.parse(url);
    // let basePageUrl = requestUrl.protocol + "//" + requestUrl.host;
    return "http://www.kuaishou.com";
}

async function $getPage (url) {
    let response = await axios.get(url);
    return cheerio.load(response.data.toString());
}

(async () => {
    try {
        //let response = await axios.get("https://www.kuaishou.com/photo/770176669/5003237056");


        //console.log(response.data);

        // fs.writeFileSync("1.html", response.data);

        let $page = await $getPage("https://www.kuaishou.com/photo/770176669/5003237056");

        let info = getUserInfo($page);
        let list = getOtherVideo($page);

        console.log(info);
        console.log(list);

        for (let i = 0; i < list.length; ++i) {
            let imageStream = await getWebFileStream(list[i].imgUrl);
            let imageBuffer = await streamToBufferAsync(imageStream);
            // console.log(imageBuffer.length);
            // let isExist = await bll.imageIsExist(list[i].imgUrl);
            // if (isExist) {
            //     console.log("存在过了");
            // }
            // else {
            //     await bll.insertImage(info.kuaiShouId , list[i].workId, false, list[i].imgUrl, imageBuffer);
            //     console.log("插入数据");
            // }
        }

        let ss = await bll.getImage("5003237056");
        fs.writeFileSync("kk.jpg", ss.buf.buffer, "binary");


        // let videoUrl = $("video").attr("src");
        // console.log(videoUrl);
        // let videoStream = await getWebFileStream(videoUrl);
        // let videoBuffer = await streamToBufferAsync(videoStream);

        // console.log(videoBuffer.length);


        // await fileDownload(videoUrl, "1.mp4");




        // let video = await getCollection();

        // await video.insert({
        //     "test": buf
        // });

        // console.log($a.attr("href"));


        //await getUserInfo($totalInfo);

        // console.log(response.data);
        // await getHttpFile("https://tx2.a.yximgs.com/uhead/AB/2017/11/07/19/BMjAxNzExMDcxOTExNTBfNzE1MzUyOTYwXzJfaGQzM182Mzk=_s.jpg");

    }
    catch (e) {
        console.log(e);
    }

})();




let obj = {

};

module.exports = obj;